import { useState } from 'react'
import { Table, Space, Button , Popconfirm, message , Modal , Form , Input , InputNumber , Badge , Tooltip , Upload} from 'antd'
import { useAntdTable } from 'ahooks'
import { ColumnsType } from 'antd/lib/table'
import { pageGoal , deleteGoal , addOrUpdateGoal , detailGoal , pushGoal } from '@/service/goal'
import { useNavigate } from 'react-router-dom'
import { formatTime } from '@/utils'
import './index.less'


export default function () {

  const { tableProps , run:reload } = useAntdTable(async ({ current , pageSize}) => {
    const {records , total } = await pageGoal({
      current,
      pageSize
    })
    return {
      total,
      list:records
    }
  })

  const navigate = useNavigate()

  const [form] = Form.useForm()
  
  const [ pushForm ] = Form.useForm()

  const [visible, setVisible] = useState<boolean>(false)
  
  const [ isUpdate , setIsUpdate ] = useState<boolean>(false)

  const columns:ColumnsType<App.GoalItem> = [
    {
      title: "目标",
      dataIndex: 'title',
      align:'center'
    },
    {
      title: "用户",
      dataIndex:'user_id',
      align: 'center',
      render:()=> 'story'
    },
    {
      title: '年度',
      dataIndex: 'goal_year',
      align:'center'
    },
    {
      title: "状态",
      dataIndex: 'goal_status',
      align: 'center',
      render: (_, record) => {
        const { finish_num , all_num } = record
        const statusArr = [
          { type:'error' , value:'未开始' },
          { type: 'processing', value: '进行中' },
          { type:'success' , value:'已完成'}
        ]
        const current =
          finish_num === 0
            ? statusArr[0]
            : finish_num < all_num
              ? statusArr[1]
              : statusArr[2];
        return (
          <Space>
            <Badge status={current.type as any} />
            <span>{ current.value }</span>
          </Space>
        )
      }
    },
    {
      title: "类型",
      dataIndex:'goal_type',
      align: 'center',
    },
    {
      title: "进度",
      align: 'center',
      render: (_, record) => {
        const { all_num, finish_num } = record;
        return (
          <Tooltip title={`${finish_num }/${all_num}`}>
            {`${ ((finish_num / all_num)*100).toFixed(1) }%` }
          </Tooltip>
        )
      }
    },
    {
      title: "标签",
      dataIndex: 'tag',
      align:'center'
    },
    {
      title: "创建时间",
      align: 'center',
      render:(_ , record)=> formatTime(record.create_time)
    },
    {
      title: "更新时间",
      dataIndex:'updated_time',
      align:'center',
      render:(_ , record)=> formatTime(record.updated_time)
    },
    {
      title: "操作",
      align:'center',
      render: (_ , record) => {
        return (
          <Space>
            <Popconfirm
              title="确认是否删除"
              onConfirm={async () => {
                const response = await deleteGoal({ id: record.id })
                if (response) {
                  message.success("删除成功")
                  reload({...tableProps.pagination})
                } else {
                  message.error("删除失败")
                }
              }}
            >
              <Button type="link" size="small" danger>删除</Button>
            </Popconfirm>
            <Button
              size="small"
              type="link"
              onClick={async () => {
                setVisible(true)
                setIsUpdate(true)
                const {
                  id,
                  all_num,
                  goal_type = "",
                  tag,
                  title
                } = await detailGoal({ id: record.id }) || {};
                form.setFieldsValue({
                  id,
                  all_num,
                  tag,
                  goal_type,
                  title
                });
              }}
            >
              编辑
            </Button>
            <Button
              type="link"
              size="small"
              onClick={() => navigate(`/admin_edit/${record.id}?from=goal`)}
            >
              修改文档
            </Button>
            <Button
              type="link"
              size="small"
              onClick={() =>  setPushVisible(record.id) }
            >
              推进
            </Button>
          </Space>
        )
      }
    },
  ]

  const onAdd = () => {
    form.resetFields()
    setIsUpdate(false)
    setVisible(true)
  }

  const onPublish = async () => {
    const params = form.getFieldsValue();
    await form.validateFields()
    const response = await addOrUpdateGoal(params)
    if (response) {
      message.success(`${isUpdate ? '更新' : '新增' }成功`);
      setVisible(false)
      reload({...tableProps.pagination})
    } else {
      message.error(`${ isUpdate ? '更新' : '新增'}失败，请重新尝试`)
    }
  }


  // ------- 推进目标 --------

  const [ pushVisible, setPushVisible ] = useState<number>(0)

  const onPush = async () => {
    const { step } = pushForm.getFieldsValue();
    await pushForm.validateFields();
    const response = await pushGoal({ id: pushVisible, step })
    if (response) {
      message.success(`推进成功`);
      setPushVisible(0)
      reload({...tableProps.pagination})
    } else {
      message.error(`推进成功失败，请重新尝试`)
    }
  }

  return (
    <div>
      <div className="action">
        <Button type="primary" onClick={onAdd}>新增</Button>
      </div>
      <Table bordered size="small" columns={columns} {...tableProps} rowKey="id" />
      <Modal
        title="发布"
        open={visible}
        onCancel={() => setVisible(false)}
        forceRender
        onOk={onPublish}
        bodyStyle={{paddingTop:'20px'}}
      >
        <Form
          layout="horizontal"
          form={form}
          size="small"
        >
          <Form.Item label="" name="id" style={{display:'none'}}>
            <Input max={50}/>
          </Form.Item>
          <Form.Item label="名称" name="title" rules={[{required :true , message:'必填'}]}>
            <Input placeholder="请输入目标名称" max={50}/>
          </Form.Item>
          <Form.Item label="指标" name="all_num" rules={[{required :true,message:'必填'}]}>
            <InputNumber placeholder="请输入总指标" style={{width:'100%'}}/>
          </Form.Item>
          <Form.Item label="类型" name="goal_type"  rules={[{required :true,message:'必填'}]}>
            <Input placeholder="请输入目标类型" />
          </Form.Item>
          <Form.Item label="标签" name="tag"  rules={[{required :true,message:'必填'}]}>
            <Input placeholder="请输入目标标签" />
          </Form.Item>
        </Form>
      </Modal>
      <Modal
        title="推进目标"
        open={Boolean(pushVisible)}
        onCancel={() => setPushVisible(0)}
        forceRender
        onOk={onPush}
        bodyStyle={{paddingTop:'20px'}}
      >
        <Form labelCol={{ span: 4 }} labelAlign="left" form={pushForm} initialValues={{step:1}}>
          <Form.Item label="推进步长" name="step">
            <InputNumber/>
          </Form.Item>
          <Form.Item label="文件" name="file">
            <Upload fileList={ []}>
              <Button>上传</Button>
            </Upload>
          </Form.Item>
        </Form>
      </Modal>
    </div>
  )
}